package com.cn.wanxi.controller;

import com.cn.wanxi.common.RedisNumTool;
import com.cn.wanxi.common.ResultCode;
import com.cn.wanxi.entity.ResultEntity;
import com.cn.wanxi.entity.UserEntity;
import com.cn.wanxi.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;

import static com.cn.wanxi.common.ParseTool.MD5;

@RestController
public class LoginController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/login")
    public ResultEntity login(UserEntity userEntity, HttpServletRequest req){
        String codeWeb = req.getParameter("code");                   //前端输入的验证码
        Jedis jedis = new Jedis();
        jedis.select(RedisNumTool.REDIS_LOGIN_CODE);
        String code = jedis.get("code");                                //后端产生的验证码

        /*验证码判断*/
        if (!code.equals(codeWeb)) {
            return ResultEntity.failed("验证码错误");
        }

        userEntity.setPassword(MD5(userEntity.getPassword()));
        ResultEntity resultModel = userService.login(userEntity);

        /*设置session*/
        if (resultModel.getCode() == ResultCode.SUCCESS.getCode()) {
            req.getSession().setAttribute("loginUsername", userEntity.getUsername());
            return ResultEntity.success(null);
        }
        return ResultEntity.failed("账号或密码错误");
    }
}
